// API基础配置
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3001/api';

// 模拟数据 - 在实际应用中应该删除
const mockContacts = [
  { id: 1, name: '张伟', phone: '138****1234', relationship: '家人' },
  { id: 2, name: '李芳', phone: '139****5678', relationship: '朋友' },
  { id: 3, name: '王明', phone: '136****9012', relationship: '同事' },
  { id: 4, name: '赵敏', phone: '137****3456', relationship: '家人' }
];

// 通用请求函数
const request = async (endpoint, options = {}) => {
  const url = `${API_BASE_URL}${endpoint}`;
  
  try {
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
};

// 获取紧急联系人列表
export const getContacts = async () => {
  // 实际API调用 - 取消注释以使用真实后端
  /*
  return await request('/emergency-contacts');
  */
  
  // 模拟API响应
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        data: mockContacts
      });
    }, 800);
  });
};

// 提交报警
export const sendAlert = async (alertData) => {
  // 实际API调用 - 取消注释以使用真实后端
  /*
  return await request('/emergency-alert', {
    method: 'POST',
    body: JSON.stringify(alertData)
  });
  */
  
  // 模拟API响应 - 90%成功率
  const isSuccess = Math.random() > 0.1;
  
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (isSuccess) {
        resolve({
          success: true,
          message: '报警成功！紧急联系人已收到通知，救援人员正在赶往现场。'
        });
      } else {
        reject({
          success: false,
          message: '网络连接失败，请检查网络后重试。'
        });
      }
    }, 2000);
  });
};